﻿<template>
  <s-layout
    title="首页"
    navbar="custom"
    tabbar="/pages/index/index"
    :navbarStyle="{ 
      ...template.style?.navbar,
      background: 'transparent',
      color: '#fff',
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      zIndex: 9999
    }"
    onShareAppMessage
  >
    <scroll-view
      scroll-y
      class="main-scroll"
      :refresher-enabled="true"
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
    >
      <view
        class="banner-container"
        :style="{ height: bannerHeight + 'px' }"
        v-if="bannerList.length > 0"
      >
        <swiper
          class="banner-swiper"
          :indicator-dots="false"
          :autoplay="true"
          :interval="3000"
          :duration="500"
          :circular="true"
          indicator-color="rgba(255,255,255,0.3)"
          indicator-active-color="rgba(255,255,255,0.8)"
        >
          <swiper-item
            v-for="(banner, index) in bannerList"
            :key="index"
            @tap="handleBannerClick(banner)"
          >
            <image 
              class="banner-image" 
              :src="banner.path" 
              mode="aspectFill" 
              @load="onImageLoad"
            />
            <view class="banner-overlay"></view>
          </swiper-item>
        </swiper>
        
        <!-- 自定义导航栏 -->
        <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
          <view class="navbar-content">
          </view>
        </view>
      </view>

      <view
        class="banner-placeholder"
        v-else
      >
        <view class="placeholder-content">
          <text class="placeholder-text">暂无轮播图</text>
        </view>
      </view>

      <view class="modules-container">
        <view class="modules-grid">
          <view
            class="module-item"
            v-for="(module, index) in moduleList"
            :key="index"
            @tap="handleModuleClick(module)"
          >
            <view class="module-icon" :class="`icon-${module.dictValue}`">
              <image 
                v-if="module.iconPath" 
                class="module-image" 
                :src="module.iconPath" 
                mode="aspectFit"
              />
              <text v-else class="module-emoji">{{
                getIconEmoji(module.dictValue)
              }}</text>
            </view>
            <text class="module-name">{{ module.dictLabel }}</text>
          </view>
        </view>
      </view>

      <view class="special-zone" v-if="activityList.length > 0">
        <image 
          class="special-image" 
          :src="activityList[0].path" 
          mode="widthFix"
          @tap="handleActivityClick(activityList[0])"
        />
      </view>

      <view class="content-container">
        <TabRecommend ref="recommendRef" />
      </view>
    </scroll-view>
  </s-layout>
</template>

<script setup>
import { computed, ref, onMounted } from "vue";
import {
  onLoad,
  onPageScroll,
  onPullDownRefresh,
  onReachBottom,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import sheep from "@/sheep";
import $share from "@/sheep/platform/share";
import TabRecommend from "./components/tab-recommend.vue";

import weixin from "@/sheep/libs/sdk-h5-weixin";

const template = computed(() => sheep.$store("app").template.home);
const barHeight = ref(0);
const statusBarHeight = ref(0);
const refresherTriggered = ref(false);
const bannerList = ref([]);
const moduleList = ref([]);
const moduleIconList = ref([]);
const activityList = ref([]);
const recommendRef = ref(null);
const bannerHeight = ref(750);

function onImageLoad(e) {
  const { width, height } = e.detail;
  const screenWidth = uni.getSystemInfoSync().screenWidth;
  const calculatedHeight = (height / width) * screenWidth;
  bannerHeight.value = calculatedHeight + statusBarHeight.value;
}

async function getBannerData() {
  try {
    const res = await sheep.$api.noAuth.getHomeMedia("banner");
    if (Array.isArray(res)) {
      bannerList.value = res;
    } else if (res && res.code === 200 && Array.isArray(res.data)) {
      bannerList.value = res.data;
    } else {
      bannerList.value = [];
    }
  } catch (error) {
    bannerList.value = [];
  }
}

async function getActivityData() {
  try {
    const res = await sheep.$api.noAuth.getHomeMedia("activity");
    if (Array.isArray(res)) {
      activityList.value = res;
    } else if (res && res.code === 200 && Array.isArray(res.data)) {
      activityList.value = res.data;
    } else {
      activityList.value = [];
    }
  } catch (error) {
    activityList.value = [];
  }
}

async function getModuleIcons() {
  try {
    const res = await sheep.$api.noAuth.getHomeMedia("types");
    if (Array.isArray(res)) {
      moduleIconList.value = res;
    } else if (res && res.code === 200 && Array.isArray(res.data)) {
      moduleIconList.value = res.data;
    } else {
      moduleIconList.value = [];
    }
  } catch (error) {
    moduleIconList.value = [];
  }
}

async function getModuleTypes() {
  try {
    const res = await sheep.$api.noAuth.getHomeTypes();
    let dictList = [];
    
    if (res && Array.isArray(res)) {
      dictList = res.sort((a, b) => a.dictSort - b.dictSort);
    } else {
      dictList = [
        { dictCode: 188, dictSort: 1, dictLabel: "关注", dictValue: "1" },
        { dictCode: 189, dictSort: 2, dictLabel: "推荐", dictValue: "2" },
        { dictCode: 190, dictSort: 3, dictLabel: "视频", dictValue: "3" },
        { dictCode: 191, dictSort: 4, dictLabel: "民宿", dictValue: "4" },
        { dictCode: 192, dictSort: 5, dictLabel: "体验", dictValue: "5" },
        { dictCode: 193, dictSort: 6, dictLabel: "驿站", dictValue: "6" },
        { dictCode: 194, dictSort: 7, dictLabel: "文旅", dictValue: "7" },
        { dictCode: 195, dictSort: 8, dictLabel: "商城", dictValue: "8" },
      ];
    }

    // 合并字典数据和图标数据
    moduleList.value = dictList.map(dict => {
      const iconData = moduleIconList.value.find(icon => icon.title === dict.dictValue);
      return {
        ...dict,
        iconPath: iconData?.path || null
      };
    });
  } catch (error) {
    moduleList.value = [
      { dictCode: 188, dictSort: 1, dictLabel: "关注", dictValue: "1", iconPath: null },
      { dictCode: 189, dictSort: 2, dictLabel: "推荐", dictValue: "2", iconPath: null },
      { dictCode: 190, dictSort: 3, dictLabel: "视频", dictValue: "3", iconPath: null },
      { dictCode: 191, dictSort: 4, dictLabel: "民宿", dictValue: "4", iconPath: null },
      { dictCode: 192, dictSort: 5, dictLabel: "体验", dictValue: "5", iconPath: null },
      { dictCode: 193, dictSort: 6, dictLabel: "驿站", dictValue: "6", iconPath: null },
      { dictCode: 194, dictSort: 7, dictLabel: "文旅", dictValue: "7", iconPath: null },
      { dictCode: 195, dictSort: 8, dictLabel: "商城", dictValue: "8", iconPath: null },
    ];
  }
}

function handleBannerClick(banner) {
  if (banner.link) {
    if (banner.link.startsWith("http")) {
      window.location.href = banner.link;
    } else {
      sheep.$router.go(banner.link);
    }
  }
}

function handleActivityClick(activity) {
  if (activity.link) {
    if (activity.link.startsWith("http")) {
      window.location.href = activity.link;
    } else {
      sheep.$router.go(activity.link);
    }
  }
}

function handleModuleClick(module) {
  switch (module.dictValue) {
    case "1":
      sheep.$router.go("/pages/follow/index");
      break;
    case "2":
      sheep.$router.go("/pages/recommend/index");
      break;
    case "3":
      sheep.$router.go("/pages/video/index");
      break;
    case "4":
      sheep.$router.go("/pages/hotel/index");
      break;
    case "5":
      sheep.$router.go("/pages/experience/index");
      break;
    case "6":
      sheep.$router.go("/pages/station/index");
      break;
    case "7":
      sheep.$router.go("/pages/tourism/index");
      break;
    case "8":
      sheep.$router.go("/pages/index/category");
      break;
  }
}

function getIconEmoji(dictValue) {
  const iconMap = {
    1: "👀",
    2: "⭐",
    3: "🎬",
    4: "🏠",
    5: "🎯",
    6: "🚉",
    7: "🏞️",
    8: "🛍️",
  };
  return iconMap[dictValue] || "📱";
}

function onRefresh() {
  refresherTriggered.value = true;

  Promise.all([
    getBannerData(),
    getActivityData(),
    getModuleIcons().then(() => getModuleTypes()),
    recommendRef.value?.loadData?.(),
  ]).then(() => {
    setTimeout(() => {
      refresherTriggered.value = false;
      uni.showToast({
        title: "刷新成功",
        icon: "success",
        duration: 1000,
      });
    }, 500);
  });
}

function onLoadMore() {
  recommendRef.value?.loadMore?.();
}

onLoad(async (options) => {
  const sysInfo = uni.getSystemInfoSync();
  statusBarHeight.value = sysInfo.statusBarHeight || 20;
  barHeight.value = sysInfo.statusBarHeight * 2 + "rpx";
  init(options);
});

function init(options) {
  if (options.templateId) {
    sheep.$store("app").init(options.templateId);
  }

  if (options.spm) {
    $share.decryptSpm(options.spm);
  }

  if (options.page) {
    sheep.$router.go(decodeURIComponent(options.page));
  }

  // 处理扫码进入的scene参数，保存为spreadUid
  if (options.scene) {
    uni.setStorageSync('sceneSpreadUid', options.scene);
  }

  getBannerData();
  getActivityData();
  getModuleIcons().then(() => getModuleTypes());
  setOpenShare();
}

onShareAppMessage((res) => {
  let shareData = {
    title: "巴蜀客家 - 传承客家文化，品味地道美食",
    desc: "发现巴蜀客家的独特魅力，体验千年文化传承！",
    link: "",
    imgUrl:
      "https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/d8590190-4f28-11eb-b680-7980c8a877b8.png",
  };
  return {
    ...shareData,
  };
});

onPullDownRefresh(() => {
  onRefresh();
  setTimeout(function () {
    uni.stopPullDownRefresh();
  }, 800);
});

function setOpenShare() {
  let shareData = {
    title: "巴蜀客家 - 传承客家文化，品味地道美食",
    desc: "发现巴蜀客家的独特魅力，体验千年文化传承！",
    link: "",
    imgUrl:
      "https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/d8590190-4f28-11eb-b680-7980c8a877b8.png",
  };
  weixin.updateShareInfo(shareData);
}
</script>

<style lang="scss" scoped>
$primary-color: #8b4513;
$secondary-color: #daa520;
$accent-color: #228b22;
$text-dark: #333;
$text-light: #666;
$bg-light: #fff8dc;

.main-scroll {
  height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 50%, #f5f5f5 100%);
  padding-top: 0;
}

.banner-container {
  width: 100%;
  position: relative;
  overflow: hidden;
  margin-top: 0;

  .banner-swiper {
    width: 100%;
    height: 100%;
    border-radius: 0;

    .banner-image {
      width: 100%;
      height: 100%;
      display: block;
      border-radius: 0;
      object-fit: cover;
    }

    .banner-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      pointer-events: none;
    }
  }

  .custom-navbar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background: transparent;
    
    .navbar-content {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 44px;
      
      .navbar-title {
        font-size: 18px;
        font-weight: 600;
        color: #fff;
        text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
        opacity: 0.9;
      }
    }
  }

  ::v-deep .uni-swiper-dot {
    background-color: rgba(255, 255, 255, 0.3) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
  }

  ::v-deep .uni-swiper-dot-active {
    background-color: rgba(255, 255, 255, 0.9) !important;
    border: 1px solid rgba(255, 255, 255, 0.3) !important;
  }
}

.banner-placeholder {
  width: 100%;
  height: 750rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  margin-bottom: -20rpx;

  .placeholder-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .placeholder-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.modules-container {
  background: #fff;
  padding: 50rpx 20rpx 30rpx;
  margin-top: -30rpx;
  border-radius: 30rpx 30rpx 0 0;
  position: relative;
  z-index: 2;

  .modules-grid {
    display: flex;
    flex-wrap: wrap;

    .module-item {
      width: 25%;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 30rpx;

      .module-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 24rpx;
        margin-bottom: 10rpx;
        transition: all 0.3s ease;

        .module-emoji {
          font-size: 48rpx;
        }
        
        .module-image {
          width: 60rpx;
          height: 60rpx;
        }

        &:active {
          transform: scale(0.95);
          box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.15);
        }
      }

      .module-name {
        font-size: 32rpx;
        color: $text-dark;
        text-align: center;
        font-weight: 500;
      }
    }
  }
}

.special-zone {
  padding: 20rpx 0;
  background: #fff;

  .special-image {
    width: 100%;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  }
}

.content-container {
  background: #fff;
  padding-bottom: 20rpx;
}
</style>
